package ltd.sshine.networkserver.runner;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.json.JsonObjectDecoder;
import io.netty.handler.codec.string.StringEncoder;
import ltd.sshine.networkserver.handler.ServerAuthChannelHandler;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class ServerRunner implements CommandLineRunner, DisposableBean {
    @Value("${system.port}")
    private int port;
    private ChannelFuture channelFuture;
    private final NioEventLoopGroup group = new NioEventLoopGroup();

    @Override
    public void destroy() throws Exception {
        group.shutdownGracefully();
        if (channelFuture != null)
            channelFuture.channel().close();
    }

    @Override
    public void run(String... args) throws Exception {
        ServerBootstrap serverBootstrap = new ServerBootstrap()
                .group(group)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nssc) throws Exception {
                        JsonObjectDecoder jsonObjectDecoder = new JsonObjectDecoder();
                        StringEncoder stringEncoder = new StringEncoder();
                        nssc.pipeline().addLast(
                                jsonObjectDecoder,
                                stringEncoder,
                                new ServerAuthChannelHandler(jsonObjectDecoder, stringEncoder)
                        );
                    }
                });
        channelFuture = serverBootstrap.bind(port);
    }
}
